package atom.message 
{
	/**
	 * A simple Observer Pattern implementation.
	 * @author Jorge Braccini
	 */
	public class MessageDispatcher {
		
		private var _listeners:Object;
		
		public function MessageDispatcher() {
			_listeners = { };
		}
		
		public function addListener(type:String, handler:Function):void {
			if (!_listeners[type]) _listeners[type] = [];
			_listeners[type].push(handler);
		}
		
		public function removeListener(type:String, handler:Function):void {
			var list:Array = _listeners[type];
			if (list) {
				var l:int = list.length, r:Number;
				for (var i:int = 0; i < l; i ++) {
					if (list[i] === handler) {
						r = i;
						break;
					}
				}
				
				if (!isNaN(r)) {
					list.splice(r, 1);
					if (list.length == 0) _listeners[type] = null;
				}
			}
		}
		
		public function dispatchMessage(message:Message):void {
			var list:Array = _listeners[message.type];
			if (list) {
				var l:int = list.length, h:Function;
				for (var i:int = 0; i < l; i++) {
					h = list[i];
					h(message);
				}
			}
		}
		
	}

}